<?php
/**
 * 导出云鲸扫地机器人设计师征集令数据
 * 每天上午10点发送头一天的数据
 */
ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING ^ E_DEPRECATED);
ini_set('memory_limit', '1024M');

require_once '/data/wwwroot/g_vendor/autoload.php';

use Biz\model\activity\NarwalDesigner as mNarwalDesigner;
use Biz\tools\Mail;
use Doraemon\model\Member as mMember;
use Doraemon\model\Phone;
use Doraemon\service\Member\PhoneCrypto;
use Doraemon\service\User;
use Doraemon\tools\ImgUrl;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;

$startTime = $argv[1] ?? date("Y-m-d", strtotime("-1 day", time()));
$endTime = $argv[2] ?? date('Y-m-d H:i:s', strtotime($startTime) + 86399);

$pageId = 844;
$pageTitle = '云鲸扫地机器人设计师征集令' . $startTime . '-提交记录';

$where = [
    'addtime[>=]' => $startTime,
    'addtime[<=]' => $endTime,
];
var_dump($where);
$list = mNarwalDesigner::selectListByCondition($where);
$uids = array_column($list, 'uid');
$uids = array_unique(array_filter($uids));
$data = [];
$userList = User::getBatchBasicUserInfo($uids);
$userList = array_column($userList, null, 'uid');
foreach ($list as $row) {
    $userInfo = [];
    $uid = $row['uid'];
    if ($uid) {
        $userInfo = (isset($userList[$uid])) ? $userList[$uid] : [];
    } else if ($row['phone']) {
        $encrypt_phone = PhoneCrypto::encrypt($row['phone'], PhoneCrypto::CLIENT_YAPI, PhoneCrypto::VERSIN);
        $uid = Phone::getUidByPhone($encrypt_phone);
        $userInfo = User::getBasicUserInfo($uid);
    }

    $designOriginImgUrl = $row['design_img'] ? ImgUrl::getBizOriginUrl($row['design_img']) : '';
    $designImgUrl = $row['design_img'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $row['design_img'], ImgUrl::IMAGE_SIZE_SQ_PHONE) : '';
    $designImgPath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'designImg' . DIRECTORY_SEPARATOR;
    if (!file_exists($designImgPath)) {
        mkdir($designImgPath);
    }
    $designImgFile = $designImgPath . $row['id'];
    if (!file_exists($designImgFile)) {
        download($designImgUrl, $designImgFile);
    }

    $elevationOriginImgUrl = $row['elevation_img'] ? ImgUrl::getBizOriginUrl($row['elevation_img']) : '';
    $elevationImgUrl = $row['elevation_img'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $row['elevation_img'], ImgUrl::IMAGE_SIZE_SQ_PHONE) : '';
    $elevationImgPath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'elevationImg' . DIRECTORY_SEPARATOR;
    if (!file_exists($elevationImgPath)) {
        mkdir($elevationImgPath);
    }
    $elevationImgFile = $elevationImgPath . $row['id'];
    if (!file_exists($elevationImgFile)) {
        download($elevationImgUrl, $elevationImgFile);
    }

    $data[$row['id']] = [
        'uid' => $uid ?? '',
        'nick' => $userInfo ? $userInfo['nick'] : $row['nick'],
        'type' => $userInfo ? mMember::$typeDesc[$userInfo['type']] : '',
        'water_position' => $row['water_position'],
        'install_position' => $row['install_position'],
        'connect_water' => $row['connect_water'],
        'more_beautiful' => $row['more_beautiful'],
        'house_suggest' => $row['house_suggest'],
        'design_img' => $designImgFile,
        'design_img_url' => $designOriginImgUrl,
        'elevation_img' => $elevationImgFile,
        'elevation_img_url' => $elevationOriginImgUrl,
        'name' => $row['name'],
        'phone' => $row['phone'],
        'area' => $row['area'] ? $row['area'] : ($userInfo ? $userInfo['area'] : ''),
        'addtime' => $row['addtime']
    ];
}
$title = ['uid', '昵称', '用户类型', '水源位置', '安装位置', '如何连接上下水', '如何提升美观性', '适用家庭建议', '效果图', '效果图片链接', '立面图', '立面图片链接', '姓名', '手机号', '所在城市', '提交时间'];

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$titCol = 'A';
foreach ($title as $key => $value) {
    // 单元格内容写入
    $sheet->setCellValue($titCol . '1', $value);
    $styleArray = [
        'alignment' => [
            'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
            'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
        ],
    ];
    $sheet->getStyle($titCol . '1')->applyFromArray($styleArray);
    $titCol++;
}
$sheet->getColumnDimension('A')->setWidth(12);
$sheet->getColumnDimension('B')->setWidth(15);
$sheet->getColumnDimension('C')->setWidth(15);
$sheet->getColumnDimension('D')->setWidth(20);
$sheet->getColumnDimension('E')->setWidth(25);
$sheet->getColumnDimension('F')->setWidth(50);
$sheet->getColumnDimension('G')->setWidth(50);
$sheet->getColumnDimension('H')->setWidth(30);
$sheet->getColumnDimension('I')->setWidth(100);
$sheet->getColumnDimension('J')->setWidth(30);
$sheet->getColumnDimension('K')->setWidth(100);
$sheet->getColumnDimension('L')->setWidth(30);
$sheet->getColumnDimension('M')->setWidth(15);
$sheet->getColumnDimension('N')->setWidth(20);
$sheet->getColumnDimension('O')->setWidth(20);
$sheet->getColumnDimension('P')->setWidth(20);

$row = 2; // 从第二行开始
foreach ($data as $id => $item) {
    $dataCol = 'A';
    foreach ($item as $key => $value) {
        $cellKey = $dataCol . $row;
        if (in_array($key, ['design_img', 'elevation_img'])) {
            $drawing[$cellKey] = new Drawing();
            $drawing[$cellKey]->setName('图片');
            $drawing[$cellKey]->setDescription('图片');
            $drawing[$cellKey]->setPath($value);
            $drawing[$cellKey]->setWidth(200);
            $drawing[$cellKey]->setHeight(200);
            $drawing[$cellKey]->setCoordinates($cellKey);
            $drawing[$cellKey]->setOffsetX(10);
            $drawing[$cellKey]->setOffsetY(10);
            $drawing[$cellKey]->setWorksheet($sheet);
        } else if (in_array($dataCol, ['J', 'L'])) {
            $sheet->setCellValue($cellKey, '下载原图');
            $sheet->getCell($cellKey)->getHyperlink()->setUrl($value);
            $sheet->getStyle($cellKey)->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_BLUE);
        } else {
            $sheet->setCellValue($cellKey, $value);
            $sheet->getStyle($cellKey)->getAlignment()->setWrapText(true);
        }
        $sheet->getRowDimension($row)->setRowHeight(200);
        $styleArray = [
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
            ],
        ];
        $sheet->getStyle($cellKey)->applyFromArray($styleArray);
        $dataCol++;
    }
    $row++;
}
$fileName = $pageTitle . '-' . time() . '.xlsx';
$filePath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $fileName;
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $fileName . '"');
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header('Pragma: public'); // HTTP/1.0
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save($filePath);
var_dump('导出成功');

$email = ['tangyiwan@haohaozhu.com'];
$email = [
    'tangyiwan@haohaozhu.com',
    'zhaojinfang@haohaozhu.com',
    'lishaolong@haohaozhu.com',
    'helei@haohaozhu.com',
    'gumei@haohaozhu.com',
    'niejinqiu@haohaozhu.com'
];
Mail::send($email, $pageTitle, $pageTitle . '</br>见附件', $filePath);
var_dump('发送邮件成功');

function download($url, $filename)
{
    var_dump('下载图片#file:' . $filename . '#url:' . $url);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
    $file = curl_exec($ch);
    curl_close($ch);
    $resource = fopen($filename, 'a');
    fwrite($resource, $file);
    fclose($resource);
    return $filename;
}
